package com.qiangesoft.calendar.mxnzp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qiangesoft.calendar.entity.CalendarConfig;
import com.qiangesoft.calendar.service.CalendarConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

/**
 * 日历数据生成 定时器执行者
 *
 * @author qiangesoft
 * @date 2023-09-29
 */
@Slf4j
@Component
public class CalendarTask {

    @Autowired
    private CalendarConfigService calendarConfigService;

    /**
     * 规则可设置为每日或者每月执行一次
     */
    @Scheduled(cron = "0 0 10 * * ?")
    public void action() {
        log.info("Create calendar data start======================>");
        // 生成未来五年的数据
        LocalDate thisYearFirstDay = LocalDate.now().with(TemporalAdjusters.firstDayOfYear());
        for (int i = 0; i < 5; i++) {
            LocalDate localDate = thisYearFirstDay.plusYears(i);
            this.doCreate(localDate);
        }
        log.info("Create calendar data finish<======================");
    }

    /**
     * 日历数据生成
     *
     * @param firstDay
     */
    private void doCreate(LocalDate firstDay) {
        int year = firstDay.getYear();
        log.info("Create {}year calendar data start!", year);

        LambdaQueryWrapper<CalendarConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CalendarConfig::getYear, year);
        long count = calendarConfigService.count(queryWrapper);
        if (count > 0) {
            log.info("Calendar data already created, do nothing!");
            return;
        }

        LocalDate lastDay = firstDay.plusYears(1);
        List<CalendarConfig> calendarConfigList = new ArrayList<>();
        LocalDate localDate = firstDay;
        while (lastDay.isAfter(localDate)) {
            CalendarConfig calendarConfig = new CalendarConfig();
            calendarConfig.setYear(year);
            calendarConfig.setMonth(localDate.getMonthValue());
            calendarConfig.setDate(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            int week = localDate.getDayOfWeek().getValue();
            calendarConfig.setWeekDay(week);
            if (week == 6 || week == 7) {
                calendarConfig.setType("1");
            } else {
                calendarConfig.setType("0");
            }
            calendarConfigList.add(calendarConfig);

            localDate = localDate.plusDays(1);
        }
        calendarConfigService.saveBatch(calendarConfigList);

        log.info("Create {}year calendar data finish!", year);
    }
}
